import React, { useState, useEffect } from "react";
import { Button, Space, message } from "antd";
import { PlayCircleOutlined, StopOutlined, ReloadOutlined } from "@ant-design/icons";
import { invoke } from "@tauri-apps/api/core";
import { useLoading } from "./LoadingProvider"; // 引入你的 Loading hook

const FrpcServerActions: React.FC = () => {
  const [runStatus, setRunStatus] = useState<number>(0);
  const [loading, setLoading] = useState<boolean>(false);
  const [messageApi, contextHolder] = message.useMessage();
  const { showLoading, hideLoading } = useLoading(); // 使用全局 loading

  useEffect(() => {
    const initServer = async () => {

      try {
        const result: any = await invoke("frpc_check");
        if (result.code) setRunStatus(result.data);
      } catch {
        setRunStatus(0);
      }
    };
    initServer();
  }, []);

  const handleRun = async () => {
    showLoading();
    try {
      const result: any = await invoke("frpc_run");
      if (result.code) {
        messageApi.success(result.msg);
        setRunStatus(1);
      } else {
        messageApi.error(result.msg);
      }
    } catch {
      messageApi.error("启动失败");
    } finally {
      hideLoading();
    }
  };

  const handleStop = async () => {
    setLoading(true);
    try {
      const result: any = await invoke("frpc_stop");
      if (result.code) {
        messageApi.success(result.msg);
        setRunStatus(0);
      } else {
        messageApi.error(result.msg);
      }
    } catch {
      messageApi.error("停止失败");
    } finally {
      setLoading(false);
    }
  };

  const handleReload = async () => {
    showLoading();
    try {
      const result: any = await invoke("frpc_reload");
      if (result.code) {
        messageApi.success(result.msg);
      } else {
        messageApi.error(result.msg);
      }
    } catch {
      messageApi.error("重载失败");
    } finally {
      hideLoading();
    }
  };

  return (
    <>
      {contextHolder}
      <Space>
        {runStatus === 0 ? (
          <Button
            type="primary"
            icon={<PlayCircleOutlined />}
            loading={loading}
            onClick={handleRun}
          >
            启动
          </Button>
        ) : (
          <>
            <Button
              danger
              icon={<StopOutlined />}
              loading={loading}
              onClick={handleStop}
            >
              停止
            </Button>
            <Button
              icon={<ReloadOutlined />}
              loading={loading}
              onClick={handleReload}
            >
              重载
            </Button>
          </>
        )}
      </Space>
    </>
  );
};

export default FrpcServerActions;
